<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * lifebalanz -  data handle 
 * save file_data to database
 * file_path : /lb_upload/
 */
class Datahandle extends CI_Controller {

	public 	$db; 					// db handler
	private $tid   	= null; 		// ower user id
	private $token	= null; 		// token
	private $qquptable	= null; 		// qq upload temp table
	private $file 	= null; 		// file save 
	public  $error 	= array();		// store save error, if there is a error, do not delete the file
	public 	$version;
	public 	$qqupload_update_users = array(); // new data , set update on if user join qqhealth

	public function __construct(){
		parent::__construct();
		$this->load->helper("common");
		// load file handle functions
		$this->load->helper('file');
		// load model
		$this->load->model('user_data');
		$this->db = $this->user_data->db;

		$info = $this->input->post('info');
		
		if(!empty($info['file_name'])){
			// var_dump($info);
			$this->file = $info['full_path'];


			$this->_fileHandle($info['orig_name']);



			exit;
		}
		
	}

	/**
	 * [index handle files save from user, and save to database]
	 * @return [type] [description]
	 */
	public function index($limit = 5){

		$limit_c = $this->config->item('file_handle_limit');
		$limit = $limit_c ? $limit_c : $limit;

		// data file dir
		$dir = $this->config->item('upload_path');

		// echo $dir;
		$fArr = get_dir_file_info($dir);
		$count = 0;
		if($fArr){
			foreach ($fArr as $v) {
				if($count >= $limit){
					break;
				}
				if(is_file($v['server_path'])){
					$this->file = $v['server_path'];
					$this->_fileHandle($v['name']);
				  	$count++;	
				}
				  
			}
		}

	}

	/**
	 * delete the current file
	 * @return [type] [description]
	 */
	private function _rmFile(){
		if(is_file($this->file)){
			unlink($this->file);
			$this->file =  null;
		}
	}

	/**
	 * [_checkUserId check if it is a valid user]
	 * @return [type] [description]
	 */
	private function _checkUserId(){
		$where = array('tid'=>$this->tid,'token'=>$this->token);
		if(!$this->db->get_where('user_token',$where)){
			// delete the wrong file
			$this->_rmFile();
			return false;
		}
		return true;
	}


	/**
	 * [_fileHandle description]
	 * @param  [type] $file [description]
	 * @return [type]       [description]
	 */
	private function _fileHandle($orig_name){
		
		// var_dump($this->file);die;
		$name =  substr($orig_name,0,strpos($orig_name, strrchr($orig_name, '.')) );
		$arr = explode('@##@', trim($name));
		// get user_id from filename
		if(count($arr) == 2){
			$this->tid   		= $arr[0];
			$this->token 		= $arr[1];
		}else{
			// wrong filename
			// var_dump('wrong file');
			$this->_rmFile();
			echo 'invalid filename:' . $this->file;
			// print error
			return false;
		}

		// check if it is a valid user
		if(!$this->_checkUserId()){
			echo 'unknow user id';
			return false;
		}
		// echo 'gogogo';die;
		// var_dump($this->file);
		$mime = get_mime_by_extension($this->file);

		// zip uncompress
		if(preg_match('/zip$/i',$mime)){

			// read zip file , return array data
			$data = read_zip($this->file);

			if(!empty($data) && is_array($data)){

				// user infos data
				$infos = array();
				foreach ($data as $k => $v) {
					
					if(!is_file($v)) continue;

					// image upload to S3 
					
					if(getimagesize($v)){

						// is upload to S3
						if($this->config->item('is_upload_s3')){
							$bucket = $this->config->item('s3_bucket');
							$client = get_s3client();
							if(!$client ) {
								echo "falid to upload image\n";
								continue;	
							}
							$info = pathinfo($v);
							$name = substr(md5($this->token), 0 , 16). "." . $info['extension'];

							try{
								$result = $client->putObject(array(
									'ACL'=> 'public-read',
								    'Bucket'     => $bucket,
								    'Key'        => $name,
								    'SourceFile' => $v,
								));
								// var_dump($result);
							} catch (Exception $e){
								// echo 'Message: ' .$e->getMessage();
								continue;
							}


							$infos['pic'] = $name;
						}

						
						if(is_file($v)) unlink($v);


					}


					// .json file
					if(preg_match('/.*\.json$/is', $v)){
						$str = file_get_contents($v);

						if(is_file($v)) unlink($v);

						if(!is_json($str)) continue;
						$json = json_decode($str);
						//*1 save sport data
						$this->_saveUserData($json->data);

						if(isset($json->data)) {
							unset($json->data);
						}
						
						$info = array();
						if(!empty($json)){
							foreach ($json as $k => $v) {
								if($k == 'userinfo'){
									$info['lastupdatemark'] = isset($v->lastupdatemark) ? ($v->lastupdatemark) : 0;
								}
								if(is_object($v) || is_array($v)){
									$info[$k] = json_encode($v);
								}else{
									$info[$k] = $v;
								}

							}
						}
						// var_dump($info);
						$infos = array_merge($infos,$info);
					}


				}

				//*2 save user infos
				$this->_saveUserInfo($infos);

			}


		}


		gearman_client(serialize(array('token'=>$this->token)));

		// var_dump($this->qqupload_update_users);
		// set on qq upload 
		if(!empty($this->qqupload_update_users)){
			
			foreach($this->qqupload_update_users as $k=>$v){
				$this->qqupload_update_user_set($k);
			}
			
		}

		// judge if delete file
		if(!empty($this->error)){
			foreach ($error as $k => $v) {
				if($this->file == $k){
					continue;
				}
				$this->_rmFile();
			}
		}else{
			$this->_rmFile();
		}

		
	}



	/**	
	 * [_saveUserInfo description]
	 * @param  [type] $json [description]
	 * @return [void]       [description]
	 */
	private function _saveUserInfo($data){
		$data['tid'] = $this->tid;
	
		if(count($data) < 2){
			return;
		}
		// $userinfo = json_encode($jsonArr['userinfo']);

		$table = 'user_infos';
		$where = array('tid'=>$this->tid);
		// select this day data
		$result = $this->db->select('tid')->get_where($table,$where)->row();
		if($result){
			// update
			$this->db->where($where);
			$this->db->update($table,$data);
			// var_dump($this->db->affected_rows());
			if(!$this->db->affected_rows()){
				// update error
				$this->error();
			}
		}else{
			// insert
			if($this->db->insert($table,$data)){
				return true;
			}else{
				$this->error();
			}
		}
		

	}



	/**
	 * [_saveUserData description]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	private function _saveUserData($data){
		$data = jsonObj_to_array($data);

		foreach ($data as $k => $v) {
			// save one day
			$this->_save($v);
		}


	}

	private function _save($data){

		$table = 'user_data';

		$date = $data['date'];
		$lastupdate = $data['lastUpdate'];

		$where = array('tid'=>$this->tid,'date'=>$date);
		$result = $this->db->get_where('user_data',$where)->row_array();
		
		if($result){
			// update
			if( $lastupdate > $result['lastupdate'] ){
				// update
				$array = array(
					'tid'			=>	$this->tid,
					'date'			=>	$date,
					'lastupdate' 	=>  $lastupdate,
					'data'			=>	json_encode($data),
				);
				$this->db->where($where);
				$this->db->update($table,$array);
				// var_dump($this->db->affected_rows());
				if($this->db->affected_rows() ){
					// mark user data has updated
					$this->qqupload_update_users[$this->tid] = true;
					return true;
				}

				// update error
				$this->error();
				
			}else{
				// older data , ignore
			}
		}else{
			// insert
			$array = array(
				'tid'			=>	$this->tid,
				'date'			=>	$date,
				'lastupdate' 	=>  $lastupdate,
				'data'			=>	json_encode($data),
			);

			// var_dump($array);
			if($this->db->insert($table,$array)){
				// mark user data has updated
				$this->qqupload_update_users[$this->tid] = true;

				return true;
			}else{
				$this->error();
			}
		}
	}

	/**
	 * [turn on user qq upload ]
	 * @return [type] [description]
	 */
	private function qqupload_update_user_set($tid){
		if(!$tid) return;
		$this->load->model("user_qqhealth_api");
		$db = $this->user_qqhealth_api;
		$result = $db->db->select("*")->from("user_qqhealth_api")->where(array("tid"=>$tid,"is_join"=>1))->get()->row_array();
		if($db->db->affected_rows()>0 && $result['status_step']!=1){
			// update status=1
			$db->db->where("tid",$tid);
			$db->db->update('user_qqhealth_api',array("status_step"=>1));
			// var_dump($db->db->last_query());
		}
	}

	/**
	 * error return
	 * @return [bool] [description]
	 */
	public function error(){
		$this->error[$this->file] = true;
		return false;
	}




}// class end